package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.RegexUtils;

public class KunwangBbsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		String[] regex = {
				"http://www.kunwang.com/thread-[0-9]*-1-1.html",
				"http://www.kunwang.com/forum.php\\?mod=viewthread&tid=[0-9]*&extra=.*",
				"http://www.kunwang.com/forum.php\\?tid=[0-9]*&mod=viewthread&extra=.*"
		};
		return RegexUtils.matchAny(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();

		bbs.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		Integer commnetNum = null;
		Integer clickNum = null;
		String author = null;

		Document doc = Jsoup.parse(htmltxt);

		title = doc.select("span#thread_subject").text();
		author = doc.select("div.thread-head-info a.bluelink").text();
		date = DateUtils.matchDate(doc.select("div.thread-head-info").text());
		content = HtmlCleaner.getContentHtml(url, doc.select("div.t_fsz"));

		clickNum = NumberUtils.matchNumber(doc.select("span.replies").text());
		commnetNum = NumberUtils.matchNumber(doc.select("span.views").text());

		bbs.setTitle(title);
		bbs.setContent(content);
		bbs.setDate(date);
		bbs.setUpdateUrl(url);
		bbs.setClickNum(clickNum);
		bbs.setCommentNum(commnetNum);
		bbs.setAuthor(author);
		return bbs;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if (StringUtils.isNotBlank(updateUrl)){
				UrlMeta urlMeta = CrawlHTML.responseToURL(updateUrl);
				return parserHtml(urlMeta);
			}
			return null;
		}
		return null;
	}

	public static void main(String[] args) {
		KunwangBbsAnalyse a = new KunwangBbsAnalyse();

		String url = "http://www.kunwang.com/thread-38260-1-1.html";
		System.out.println(DoMainUtils.GetDomainName(url));
		if (!a.isDetailPage(url)) {
			System.out.println("不匹配规则");
		} else {
			UrlMeta meta = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = a.parserHtml(meta);
			System.out.println(parserHtml);
//			System.out.println(a.Update(parserHtml));
		}

	}
	
}
